package com.a1573595.musicplayer.dbHelper

import android.content.Context
import android.util.Log
import com.a1573595.musicplayer.R
import com.a1573595.musicplayer.model.City
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import java.io.BufferedReader
import java.io.InputStreamReader

class DatabaseInitializer(private val context: Context) {//初始化数据库
    fun initialize() {
        val dbHelper = CityDatabaseHelper(context)

        // JSON 数据
        val json = readJsonFromRaw(R.raw.citycode)

        // 使用 Gson 解析 JSON 并存储到数据库
        val gson = Gson()
        val cityList: List<City> = gson.fromJson(json, object : TypeToken<List<City>>() {}.type)
    cityList.forEach { city ->
        Log.d("CityDebug", "City: $city")
        dbHelper.insertCity(city)
    }

    Log.d("DatabaseInitializer", "Database initialized with cities.")
        dbHelper.close() // 关闭数据库连接
    }
    private fun readJsonFromRaw(resourceId: Int): String {
        val inputStream = context.resources.openRawResource(resourceId)
        val reader = BufferedReader(InputStreamReader(inputStream))
        val builder = StringBuilder()
        reader.forEachLine { builder.append(it) }
        reader.close()
        return builder.toString()
    }
}
